# 可用角色：狼人，狼王，平民，猎人，预言家，守卫，女巫
# TODO:完成白天，修复女巫毒药判断，女巫出局判断，出局判断，配置修改，修复白天打印，NumToName,修复女巫解药，修复女巫获取刚死的人(刀盾解同一个人的逻辑)，回答完的反馈
#
import random
import colorama
import os

file = open('config.txt','w')
file.write('nb!')
file.close()
colorama.init()
Config = {
    "1": {
        "name": "狼王预守猎6人",
        "good": ["预言家", "守卫", "猎人"],
        "bad": ["狼王"],
        "langren": 1,
        "min": 1,
        "all": 6,
    },
    "2": {
        "name": "狼王预守女猎8人",
        "good": ["预言家", "守卫", "女巫", "猎人"],
        "bad": ["狼王"],
        "langren": 2,
        "min": 1,
        "all": 8,
    },
    "3": {
        "name": "狼王预守猎7人",
        "good": ["预言家", "守卫", "猎人"],
        "bad": ["狼王"],
        "langren": 2,
        "min": 1,
        "all": 7,
    },
}
NameConfig = {
    "1": {
        "name": "示例",
        "member": ["11", "22", "33", "44", "55", "66", "77", "88", "99"],
    }
}
GoodAct = ["平民", "预言家", "守卫", "女巫", "猎人"]
BadAct = ["狼人", "狼王"]
NightList = ["守卫", "狼人", "女巫", "预言家"]
ActOn = {
    "狼人": [],
    "狼王": {"Player": 0},
    "猎人": {"Player": 0},
    "预言家": {"Player": 0, "checked": []},
    "女巫": {"Player": 0, "save": 1, "kill": 1},
    "守卫": {"Player": 0, "able": 1},
}


AllAct = GoodAct + BadAct
Alive = {}
LangRen = 0
Min: int = 0
KilledRecently = []
Protect = 0
YuYan = 0
YuYaned = []
Protected = []
NightLog = {}
Day = 1


def PlayerColor(Player):
    global Alive, GoodAct, BadAct
    if Alive[Player]["act"] == "平民":
        print(colorama.Fore.BLUE + NumToName(Player), end="")
        print(colorama.Fore.RESET + " ")
    elif Alive[Player]["act"] in BadAct:
        print(colorama.Fore.RED + NumToName(Player), end="")
        print(colorama.Fore.RESET + " ")
    elif Alive[Player]["act"] in GoodAct:
        print(colorama.Fore.GREEN + NumToName(Player), end="")
        print(colorama.Fore.RESET + " ")


def ActColor(act, enter=0):
    global Alive, GoodAct, BadAct
    if act == "平民":
        print(colorama.Fore.BLUE + act, end="")
        print(colorama.Fore.RESET + "", end=" ")
    elif act in BadAct:
        print(colorama.Fore.RED + act, end="")
        print(colorama.Fore.RESET + "", end=" ")
    elif act in GoodAct:
        print(colorama.Fore.GREEN + act, end="")
        print(colorama.Fore.RESET + "", end=" ")
    if enter == 1:
        print("")


def NumNameSpace(name):
    namespace = ""
    for i in range((3 - len(NumToName(name)))):
        namespace += "  "
    return namespace


def NumActSpace(Num):
    global Alive
    actspace = ""
    for i in range(3 - len(Alive[Num]["act"])):
        actspace += "  "
    return actspace

def Clear():
    os.system("cls")
    print("\033c",end = '')

def OnPrint():
    global NameSelect, ActOn, Alive, Protect, Protected, YuYan, YuYaned
    print(
        colorama.Back.YELLOW
        + colorama.Fore.BLACK
        + "==============配置一览==============",
        end="",
    )
    print(colorama.Fore.RESET + colorama.Back.RESET + "")
    for i in range(1, len(Alive) + 1):
        print(str(i) + " " + NumToName(str(i)) + NumNameSpace(str(i)), end=" ")
        ActColor(Alive[str(i)]["act"])
        print(NumActSpace(str(i)), end="")

        if Alive[str(i)]["alive"] == 0:
            print(colorama.Back.RED + "出局", end="")
        elif Alive[str(i)]["alive"] == 1:
            print(colorama.Fore.BLACK + colorama.Back.GREEN + "在场", end="")
        print(colorama.Back.RESET + "", end=" ")

        if Protect == str(i):
            print(colorama.Fore.BLACK + colorama.Back.YELLOW + "护盾", end="")
        elif str(i) in Protected:
            print(colorama.Fore.YELLOW + "守过", end="")
        else:
            print("    ", end="")
        print(colorama.Fore.RESET + colorama.Back.RESET + "", end="")

        if str(i) == YuYan:
            print(colorama.Back.MAGENTA + "预言", end="")
        elif str(i) in YuYaned:
            print(colorama.Fore.MAGENTA + "预过", end="")
        else:
            print("    ", end="")
        print(colorama.Fore.RESET + colorama.Back.RESET + "", end=" ")

        if Alive[str(i)]["act"] == "女巫":
            if ActOn["女巫"]["save"] == 1:
                print(colorama.Fore.BLACK + colorama.Back.GREEN + "解", end="")
            else:
                print("解", end="")
            print(colorama.Fore.RESET + colorama.Back.RESET + "", end=" ")
            if ActOn["女巫"]["kill"] == 1:
                print(colorama.Back.RED + "毒", end="")
            else:
                print("毒", end=" ")
            print(colorama.Back.RESET + "", end=" ")

        if Alive[str(i)]["act"] == "守卫":
            if ActOn["守卫"]["able"] == 1:
                print(colorama.Fore.BLACK + colorama.Back.YELLOW + "盾", end="")
            else:
                print("盾", end="")
            print(colorama.Fore.RESET + colorama.Back.RESET + "", end=" ")
        print("")


def NightPrint(mode, txt):
    global NightLog, NightPrintLog, Day
    os.system("cls")
    # print("\033c",end = '')

    OnPrint()
    print("")
    print(colorama.Style.BRIGHT + "===============第" + str(Day) + "天================")
    print(colorama.Style.RESET_ALL + "", end="")
    print(colorama.Back.MAGENTA + "============天黑请闭眼==============", end="")
    print(colorama.Back.RESET + "", end="")
    print("")

    if len(NightPrintLog) != 0:
        for i in NightPrintLog:
            if i["mode"] == "tip":
                print(i["txt"])
            elif i["mode"] == "read":
                print(colorama.Fore.CYAN + i["txt"])
            elif i["mode"] == "log":
                print(colorama.Fore.YELLOW + i["txt"])
            print(colorama.Fore.RESET + "", end="")
    if mode == "tip":
        print(txt)
        NightPrintLog.append({"mode": "tip", "txt": txt})
    elif mode == "read":
        print(colorama.Fore.CYAN + txt)
        NightPrintLog.append({"mode": "read", "txt": txt})
    elif mode == "log":
        print(colorama.Fore.YELLOW + txt)
        NightPrintLog.append({"mode": "log", "txt": txt})
        NightLog[str(Day)].append(txt)
    print(colorama.Fore.RESET + "", end="")


def NightAct(act):
    global ActOn, KilledRecently, Protect, GoodAct, BadAct, YuYan, YuYaned, Protected
    if act == "狼人":
        NightPrint("read", "狼人请睁眼")
        if len(LangRenAlive()) == 0:
            if ActOn["狼王"]["Player"] == 0:
                NightPrint("tip", "无狼刀可用，跳过")
            elif ActAlive("狼王") == 0:
                NightPrint("tip", "无狼刀可用，跳过")
        NightPrint("read", "你今晚要刀谁？")
        kill = input()
        NightPrint("tip", kill)
        if kill == Protect:
            NightPrint("tip", "狼刀撞盾，盾已破")
            ActOn["守卫"]["able"] = 0
            Protect = 0
        elif kill == "0":
            NightPrint("log", "狼人空刀")
        else:
            NightPrint("log", "狼人刀了" + (NumToName(kill)))
            KilledRecently.append(kill)
            ChangePlayerAlive(kill, 0)
        NightPrint("read", "狼人请闭眼")

    else:
        NightPrint("read", act + "请睁眼")
        if ActAlive(act) == 0:
            NightPrint("tip", act + "已出局，跳过")
            NightPrint("read", act + "请闭眼")
        else:
            if act == "守卫":
                if ActOn["守卫"]["able"] == 0:
                    NightPrint("log", "守卫没有盾")
                else:
                    while Protect not in Protected:
                        NightPrint("read", "你要守谁？")
                        Protect = input()
                        NightPrint("tip", Protect)
                        if Protect in Protected:
                            NightPrint("tip", NumToName(Protect) + "守过了")
                        else:
                            NightPrint("log", "守卫守了" + (NumToName(Protect)))
                            Protected.append(Protect)

            if act == "女巫":
                if ActOn["女巫"]["save"] == 1:
                    if not KilledRecently:
                        NightPrint("tip", "昨天没有人死,不使用解药")
                elif ActOn["女巫"]["save"] == 0:
                    NightPrint("tip", "女巫没有解药")

                else:
                    NightPrint(
                        "read",
                        "昨天" + NumToName(KilledRecently[0]) + "死了，你要救ta吗？",
                    )
                    choose = input()
                    NightPrint("tip", choose)
                    if choose == 1:
                        ChangePlayerAlive(KilledRecently, 1)
                        ActOn["女巫"]["save"] = 0
                        NightPrint("log", "女巫救了" + NumToName(KilledRecently))
                    else:
                        NightPrint("tip", "女巫不使用解药")
                if ActOn["女巫"]["kill"] == 0:
                    NightPrint("tip", "女巫没有毒药")
                else:
                    NightPrint("read", "你要用毒药吗？")
                    choose = input()
                    NightPrint("tip", choose)
                    if choose == "1":
                        NightPrint("read", "你要毒谁？")
                        choose = input()
                        NightPrint("tip", choose)
                        ChangePlayerAlive(choose, 0)
                        NightPrint("log", "女巫毒了" + NumToName(choose))
                    else:
                        print("女巫不使用毒药")

            if act == "预言家":
                while YuYan not in YuYaned:
                    NightPrint("read", "你要预言谁的身份？")
                    YuYan = input()
                    NightPrint("tip", YuYan)
                    if YuYan in YuYaned:
                        NightPrint("tip", "预过了")
                    else:
                        if Alive[YuYan]["act"] in GoodAct:
                            NightPrint("tip", NumToName(YuYan) + "是好人")
                        if Alive[YuYan]["act"] in BadAct:
                            NightPrint("tip", NumToName(YuYan) + "是坏人")
                        YuYaned.append(YuYan)

        NightPrint("read", act + "请闭眼")


def ActAlive(act):
    global ActOn, Alive
    return Alive[ActOn[act]["Player"]]["alive"]


def ChangePlayerAlive(Player, alive):
    global Alive
    Alive[Player]["alive"] = alive


def NumToName(Num):
    return NameSelect[int(Num) - 1][1:]


def ActToPlayer(act):
    global LangRen, ActOn
    if act == "狼人":
        return ActOn["狼人"]
    return ActOn[act]["Player"]


def LangRenAlive():
    global LangRen, Alive
    alive = []
    for i in ActOn["狼人"]:
        if Alive[i]["alive"] == 1:
            alive.append(i)
        return alive
    return None


print("=======狼人杀自动裁判开始运行=======")

print("选择配置,0自定义")
for i in range(1, len(Config) + 1):
    print(i, end=" ")
    print(Config[str(i)]["name"])
ConfigSeclet = input()
if ConfigSeclet == "0":
    ActNum = input("多少人局？")
else:
    ConAll = input("完全按配置？")
    if ConAll == "1":
        LangRen = Config[str(ConfigSeclet)]["langren"]
        Min = Config[str(ConfigSeclet)]["min"]
        All = Config[str(ConfigSeclet)]["all"]
        #初始化Alive
        for i in range(All):
            Alive[str(i + 1)] = {"act": 0, "alive": 1}
        print("上场好人：")
        print(Config[str(ConfigSeclet)]["good"])
        print("上场坏人:")
        print(Config[str(ConfigSeclet)]["bad"])
        print("狼人数：", end="")
        print(LangRen)
        print("总人数：", end="")
        print(All)
    elif ConAll == "0":
        print("此功能还在开发")

AllActOn = Config[str(ConfigSeclet)]["good"] + Config[str(ConfigSeclet)]["bad"]
if LangRen != 0:
    AllActOn.append("狼人")
if Min != 0:
    AllActOn.append("平民")
Card = input("自动发卡？")
if Card == "1":
    RandList = []
    i = 1
    while i != All + 1:
        Rand = random.randint(1, All)
        if Rand in RandList:
            continue
        RandList.append(Rand)
        if i <= LangRen != 0:
            Alive[str(Rand)]["act"] = "狼人"
        elif LangRen < i <= LangRen + Min and Min != 0:
            Alive[str(Rand)]["act"] = "平民"
        else:
            Alive[str(Rand)]["act"] = AllActOn[i - LangRen - Min - 1]
        i += 1
print("选择成员配置：")
for i in range(len(NameConfig)):
    print(i + 1, end=" ")
    print(NameConfig[str(i + 1)]["name"])
NameSelect = NameConfig[input()]["member"]
print(NameSelect)
NameRemoveIn = input("移除的成员：")
NameRemove = NameRemoveIn.split(" ")
for i in NameRemove:
    NameSelect.pop(int(i) - 1)
print("")


os.system("cls")
# print("\033c",end = '')
print(
    colorama.Back.YELLOW + colorama.Fore.BLACK + "==============配置一览=============="
)
print(colorama.Fore.RESET + colorama.Back.RESET + "")
for i in range(1, len(Alive) + 1):
    print(str(i) + " " + NumToName(str(i)) + NumNameSpace(str(i)), end=" ")
    ActColor(Alive[str(i)]["act"], 1)
    if Alive[str(i)]["act"] == "狼人":
        ActOn["狼人"].append(str(i))
    elif Alive[str(i)]["act"] == "平民":
        continue
    else:
        ActOn[Alive[str(i)]["act"]]["Player"] = str(i)
print("")

while True:
    NightPrintLog = []
    NightLog[str(Day)] = []
    Protect = 0
    YuYan = 0
    KilledRecently = []
    for i in NightList:
        if i in AllActOn:
            NightAct(i)
        print("")
    print(
        colorama.Back.CYAN
        + colorama.Fore.BLACK
        + "===============天亮了==============="
    )
    print(colorama.Fore.RESET + colorama.Back.RESET + "")
    if not KilledRecently:
        print("昨天是平安夜")
    else:
        print("昨天", end=" ")
        for i in KilledRecently:
            print(NumToName(i), end=" ")
        print("死了")
        print('裁判现场组织投票，要投出的是')
        OutActor = input()
        print(NumToName(OutActor)+'已出局')
        Alive[OutActor]['alive']=0
    a = input('输入任意内容继续...')
    Day += 1
